<?php


namespace app\library\create\lib;

/**
 * 创建文件
 * Class CreateFile
 * @package app\library\create\lib
 */
class CreateFile
{
    private $prefix;

    /**
     * 创建文件
     * @param array $tableFields
     * @param $prefix
     */
    public static function create(array $tableFields, $prefix)
    {
        $self = new self();
        $self->prefix = $prefix;
        foreach ($tableFields as $tableField) {
            $fileName = $self->createFileName($tableField['tableName']);
            CreateModel::buildFile($fileName, $tableField, $prefix);//创建模型文件
            CreateController::buildFile($fileName, $prefix);
            UpdateRouter::update($fileName);
        }

    }


    /**
     * 创建文件名  1，转下划线小驼峰为单词首字母小驼峰 2,转首字母大写大驼峰
     * @param $name
     * @return string
     */
    private function createFileName($name)
    {
        $name = $this->camelize(str_replace($this->prefix, '', $name));
        return ucfirst($name);

    }


    /**
     * 下划线转驼峰
     * 思路:
     * step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
     * step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
     * @param $uncamelized_words
     * @param string $separator
     * @return string
     */
    function camelize($uncamelized_words, $separator = '_')
    {
        $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
        return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
    }


    /**
     * 驼峰命名转下划线命名
     * 思路:
     * @param $camelCaps
     * @param string $separator
     * @return string
     */
    function uncamelize($camelCaps, $separator = '_')
    {
        return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
    }

    public static function createFile($path, $file, $content)
    {
        self::createDirs($path);
        $fOpen = fopen($path . $file, 'w+', $content);
        fwrite($fOpen, $content);
        fclose($fOpen);
    }

    public static function updateTailToFile($file, $content)
    {
        $fOpen = fopen($file, 'a+');
        fwrite($fOpen, $content);
        fclose($fOpen);
    }

    public static function createDirs($path)
    {
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
    }
}